require('dotenv').config()
const express = require('express')
const cors = require('cors')
const http = require('http')
const socketIo = require('socket.io')
const mongoose = require('mongoose')

const app = express()
const server = http.createServer(app)

// 数据库连接
mongoose.connect(process.env.MONGODB_URI || 'mongodb+srv://gzhukun:gzk135246@cluster0.pnlj5a1.mongodb.net/smartpark', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
.then(() => console.log('MongoDB 连接成功'))
.catch(err => console.error('MongoDB 连接失败:', err))

// CORS 配置
app.use(cors({
  origin: [
    'http://localhost:3000',
    'http://127.0.0.1:3000',
    'http://localhost:3001'
  ],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}))

// Socket.IO 配置
const io = socketIo(server, {
  cors: {
    origin: [
      'http://localhost:3000',
      'http://127.0.0.1:3000'
    ],
    methods: ['GET', 'POST'],
    credentials: true
  }
})

// 中间件
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 健康检查路由
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    message: '智慧园区后端服务运行正常',
    timestamp: new Date().toISOString(),
    database: mongoose.connection.readyState === 1 ? 'connected' : 'disconnected'
  })
})

// API 路由
app.use('/api', require('./routes'))

// 注册路由
app.use('/api/auth', require('./routes/api/auth'));
app.use('/api/devices', require('./routes/api/devices'));
app.use('/api/dashboard', require('./routes/api/dashboard'));
app.use('/api/energy', require('./routes/api/energy'));
app.use('/api/security', require('./routes/api/security'));
app.use('/api/parking', require('./routes/api/parking'));

// Socket.IO 连接处理
io.on('connection', (socket) => {
  console.log('客户端已连接:', socket.id)
  
  socket.on('disconnect', () => {
    console.log('客户端已断开:', socket.id)
  })
})

const PORT = process.env.PORT || 5000

server.listen(PORT, () => {
  console.log(`智慧园区后端服务运行在端口 ${PORT}`)
  console.log(`API 地址: http://localhost:${PORT}/api`)
  console.log(`健康检查: http://localhost:${PORT}/api/health`)
})

module.exports = { app, io }
